package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.PathMatcherUtil;
import com.zzyl.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 移动端拦截器
 */
@Slf4j
@Component
public class MobileInterceptor implements HandlerInterceptor {

    @Autowired
    JwtTokenProperties jwtTokenProperties;
    @Autowired
    ResourceMapper resourceMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), jwt);
        Long id = Long.valueOf(claims.get("id").toString());
        if (ObjectUtil.isEmpty(id)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        log.info("用户信息：{}", id);


       /* List<String> list = resourceMapper.selectListByUserId(id);

        String requestURL = request.getMethod() + request.getRequestURL();

        if (!PathMatcherUtil.match(list, requestURL)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }*/
        //ThreadLocalUtil.set(id);
        ThreadLocalUtil.set(id);
        log.info("============================================={}", id);
        return true;
    }


}